# FastAPI的相关模块导入
from fastapi import FastAPI, Form, File, UploadFile, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

#
from pydantic import BaseModel, Field, ValidationError, validator, validators, EmailStr

#
from typing import Union, List, Optional
import uvicorn
from datetime import date
import sys
import os


app = FastAPI()
templates = Jinja2Templates(directory="templates") # 实例化Jinja2对象，并将文件夹路径设置为以templates名称的文件夹

@app.get("/")
def hello(request: Request):
    data = {
        "request": request,
        "user": "zhangyz",
        "books": ["西游记", "三国演义", "水浒传", "红楼梦"],
        "booksDict": {"price": 100, "publish": "水果出版社"},
    }

    return templates.TemplateResponse("hello.html", data)

@app.get("/index")
def index(request: Request):
    book_list = ["西游记", "三国演义", "水浒传", "红楼梦"]

    user = {"name": "zhangyz", "age": 29, "gender": "male"}

    data = {
        "request": request, # 模板中需要使用request对象, 必须传入不然会报错无法加载html页面
        "name": "root",
        "age": 32,
        "books": book_list,
        "info": user,
    }

    return templates.TemplateResponse("index.html", data)


if __name__ == '__main__':
    print(sys.argv)

    # 获取当前文件的完整路径
    file_path = __file__
    # 获取文件名
    file_name = os.path.basename(file_path)
    print(file_name)

    start_args = file_name.split(".py")[0] + ":app"

    uvicorn.run(start_args, host="127.0.0.1", port=8000, reload=True)